<script setup lang="ts">
import { ref, reactive } from 'vue'
import { login, getCode } from '@/api/auth/index'
import type { CodeResult, LoginParam, Token } from '@/api/auth/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/useTokenStore';
const route = useRoute()
const router = useRouter()
const tokenStore = useTokenStore()
// 验证码base64
const codeUrl = ref('')

const loginForm = ref<LoginParam>({
  username: '',
  password: '',
  uuid: '',
  code: ''
})
const loginFormRef = ref<FormInstance>()
const loginFormRules = ref<FormRules>({
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }],
  code: [{ required: true, message: '请输入密码' }]
})

/* 获取验证码 */
const getVerifyCode = () => {
  getCode().then((resp: CodeResult) => {
    codeUrl.value = resp.codeUrl
    loginForm.value.uuid = resp.uuid
  }).catch(e => {
    console.log(e)
  })
}

/* 登录 */
const comfirm = () => {
  loginFormRef.value?.validate(valid => {
    if (valid) {
        login(loginForm.value)
        .then((resp:any)=>{
          tokenStore.setToken(resp)

          ElMessage.success('登录成功')
          router.push({path: route.query.destPath? route.query.destPath as string : '/'})
        })
        .catch(e=>{
          console.log(e)
        })
    }
  })
}

const resetLoginForm = () => {
  loginFormRef.value?.resetFields()
  getVerifyCode()

}

/* ===== 进入这个页面要执行的方法 */
getVerifyCode()
</script>

<template>
  <el-card class="login-card">
    <el-form @keyup.enter="comfirm()" ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="80">

      <el-form-item label="用户名" prop="username">
        <el-input prefix-icon="User" placeholder="请输入用户名" v-model="loginForm.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input prefix-icon="Key" type="password" placeholder="请输入密码" v-model="loginForm.password" />
      </el-form-item>

      <el-row :gutter="15">
        <el-col :span="18">
          <el-form-item label="验证码" prop="code">
            <el-input prefix-icon="Code" placeholder="请输入验证码" v-model="loginForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-image :src="codeUrl" @click="getVerifyCode" />
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="info" plain @click="resetLoginForm">重置</el-button>
        <el-button type="primary" plain @click="comfirm()">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
  .login-card {
    width: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
</style>